package com.zzptc.sky.translate;


import android.os.Handler;
import android.os.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by Administrator on 2017/3/2.
 */

public class HttpUtil {

    public static void get(final String url, final Handler handler){
        //TODO 网络请求  GET方式   传入参数：URL    Handler
        //TODO 网络请求需要运行在子线程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                String json = null;
                String j;
                try {
                    URL u=new URL(url);
                    HttpURLConnection connection= (HttpURLConnection) u.openConnection();
                    connection.setRequestMethod("GET");
                    if(connection.getResponseCode()==200){
                        InputStream inputStream=connection.getInputStream();
                        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
                        while((j =bufferedReader.readLine())!=null){
                            json = j;
                        }
                        //TODO  将JSON数据通过Handler的回调方法传输过去
                        Message message = handler.obtainMessage();
                        message.obj = json;
                        handler.sendMessage(message);
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

